package com.lhn.netty.netty_demo.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

/**
 * @author lhn
 * @date 2025/06/01 17:39
 * @since 1.0.0
 **/
/**
 * SimpleChannelInboundHandler 继承 SimpleChannelInboundHandler<HttpObject>
 * HttpObject:  HttpObject 是 Netty 提供的抽象类，继承了 HttpRequest、HttpResponse、HttpContent、LastHttpContent
 *          客户端和服务端相互通信的数据 都会封装成 HttpObject
 * */
public class TestHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {

    // 读取数据使用
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, HttpObject httpObject) throws Exception {
        // 判断 msg 是不是 HttpRequest 请求
         if (httpObject instanceof HttpRequest) {
             System.out.println("收到客户端请求");
             System.out.println("pipeline" + channelHandlerContext.pipeline().hashCode()
             +  " TestHttpServerHandler" + this.hashCode());

             System.out.println("msg 类型: " + httpObject.getClass());
             System.out.println("客户端地址: " + channelHandlerContext.channel().remoteAddress());

             HttpRequest httpRequest = (HttpRequest) httpObject;
             // 获取 请求的uri
             String uri = httpRequest.uri();
             System.out.println("请求的URI: " + uri);
             if ("/favicon.ico".equals(uri)) {
                 System.out.println("请求了 favicon.ico, 不需要返回");
                 return;
             }
             // 回复信息给浏览器 http 协议
             ByteBuf content = Unpooled.copiedBuffer("Hello, I'm Server", CharsetUtil.UTF_8);
             // 构造一个 http 响应对象 即  HttpResponse
             DefaultFullHttpResponse fullHttpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);
             fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
             fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());
             channelHandlerContext.writeAndFlush(fullHttpResponse);
         }
    }
}